import { aiStudyApi } from '@/api';
import CusModal from '@/components/CusModal';
import { Button, Cascader, Input, message, Table } from 'antd';
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import SelAiModal from '../SelAiModal';
export type SelContRef = {
  onSubmit: () => Promise<any>;
};
let prevent = false;
const EditModal = forwardRef<SelContRef, any>((props, ref) => {
  const [isModalShow, setIsModalShow] = useState<{ show: boolean; type?: string; modelType?: string }>({ show: false });
  const [configModal, setConfigModal] = useState<{ title: string; children: React.ReactNode }>();
  const [modalBtnStatus, setModalBtnStatus] = useState({ loading: false, disabled: false }); //modal框按钮状态
  // if (!props.parentClassName)
  const SelAiModalRef = useRef<any>(null);
  const [adata, setAdata] = useState<any[]>([]);
  let [collaKey, setcollaKey] = useState<number>(0);
  const selAiStudyCont = (param: any) => {
    const { type } = param;
    // setModalType('matter');
    setIsModalShow({ show: true, type, modelType: 'selAiCont' });
    setConfigModal({
      title: '选择AI学习内容',
      children: <SelAiModal ref={SelAiModalRef} {...param} />,
    });
  };
  // 关闭modal
  const closeModal = () => {
    setIsModalShow({ show: false });
  };
  // 点击modal保存按钮
  const confirmModal = () => {
    setModalBtnStatus({ disabled: true, loading: true });
    if (SelAiModalRef.current) {
      SelAiModalRef.current
        ?.onSubmit()
        .then((values: any) => {
          if (values) {
            adata.forEach((el: any, index1: any) => {
              if (index1 == values.record.parIndex) {
                el.aiStudyTriggerVoList.forEach((item: any, index2: any) => {
                  if (index2 == values.record.index) {
                    item.parentClassName = values.record.parentClassName;
                    item.className = values.record.className;
                    item.classId = values.record.classId;
                    item.havePackage = 1;
                  }
                });
              }
            });

            // setColldata();
            closeModal();
            // getObjPersonNum(values);
            const arr = [...adata];
            setAdata(arr);
            setcollaKey(++collaKey);
          }
        })
        .finally(() => {
          setModalBtnStatus({ disabled: false, loading: false });
        });
      setModalBtnStatus({ disabled: false, loading: false });
    }
  };
  // modal框配置
  const modalConst = {
    open: isModalShow.show,
    width: 730,
    centered: true,
    destroyOnClose: true,
    footer: [
      <Button key="back" disabled={modalBtnStatus.disabled} onClick={closeModal}>
        取消
      </Button>,
      <Button type="primary" key="save" loading={modalBtnStatus.loading} onClick={confirmModal}>
        确定
      </Button>,
    ],
    onCancel: closeModal,
  };
  const columns = [
    {
      title: '触发条件次数',
      dataIndex: 'startNumber',
      key: 'startNumber',
      render: (text: any, record: any) => (
        <>
          <Input value={record.startNumber} style={{ width: 50, marginRight: 10 }} />
          ≤次数{record.endNumber < 999999999 ? <>＜{record.endNumber} </> : null}
        </>
      ),
    },
    {
      title: 'AI学习内容',
      dataIndex: 'classId',
      key: 'classId',
      render: (text: any, record: any) => (
        <>
          {record.havePackage == 0 ? (
            <Cascader
              style={{ width: 400, border: '1px solid #ff4d4f', borderRadius: 4 }}
              maxTagCount="responsive"
              defaultValue={['课件包', record.parentClassName, record.className]}
              allowClear={false}
              bordered={false}
              onClick={() => {
                selAiStudyCont({ type: 'add', record });
                console.log('222');
                // setAdata([]);
              }}
              // disabled={true}
              dropdownRender={() => <></>}
            />
          ) : (
            // <div style={{ width: 400, border: '1px solid #ff4d4f', borderRadius: 4 }}>
            //   课件包/{record.parentClassName + '/' + record.className}
            // </div>
            <Cascader
              style={{ width: 400 }}
              maxTagCount="responsive"
              defaultValue={['课件包', record.parentClassName, record.className]}
              allowClear={false}
              disabled={true}
            />
          )}
        </>
      ),
    },
  ];
  const onSubmit = async () => {
    return new Promise((resolve, reject) => {
      aiStudyApi.getAiContList({}).then((res: any) => {
        if (res.code == 200) {
          const resdata = res.data.list;
          // 把没有内容的分类id抛出来，然后遍历搞
          const arr: any[] = [];
          resdata.forEach((el: any) => {
            el.lowerListVo.forEach((item: any) => {
              if (item.canChoose == 0) arr.push(item.guid);
            });
          });
          let hasNoPackage = false;
          adata.forEach((el: any, index1: any) => {
            if (el.aiStudyTriggerVoList) {
              el.aiStudyTriggerVoList.forEach((obj: any, index2: any) => {
                if (arr.includes(obj.classId)) {
                  obj.havePackage = 0;
                  hasNoPackage = true;
                }
                obj.index = index2;
                obj.parIndex = index1;
              });
            } else {
              el.aiStudyTriggerDtoList.forEach((obj: any, index2: any) => {
                if (arr.includes(obj.classId)) {
                  obj.havePackage = 0;
                  hasNoPackage = true;
                }
                obj.index = index2;
                obj.parIndex = index1;
              });
            }
          });
          // 如果还有空包的规则，继续当前弹窗
          if (hasNoPackage) {
            // 重新拿次详情
            if (prevent) return;
            else {
              setTimeout(() => {
                prevent = false;
              }, 1000);
            }
            prevent = true;
            const copyarr = [...adata];
            setAdata(copyarr);
            message.error('该计划仍存在没有课件包的分类，请修改课件包分类');
          } else {
            resolve({ seledData: [...adata] });
          }
        }
      });
    });
  };
  useImperativeHandle(ref, () => ({
    onSubmit,
  }));
  useEffect(() => {
    // getEventsList();
    console.log(props.data);
    setAdata(props.data);
    setcollaKey(++collaKey);
  }, []);
  return (
    <>
      <div style={{ padding: '16px 16px 0' }}>
        {adata.map((el, index) => {
          return (
            <div key={index}>
              <div style={{ height: '30px', lineHeight: '30px', fontWeight: 'bold' }}>
                {el.groupName + '/' + el.factorName}
              </div>
              <Table key={index + collaKey} dataSource={el.aiStudyTriggerVoList} columns={columns} pagination={false} />
            </div>
          );
        })}
        <div style={{ marginTop: 10 }}>AI学习内容所选择的课件包分类中没有课件包，请修改课件包分类</div>
      </div>
      <CusModal {...modalConst} {...configModal} />
    </>
  );
});
export default EditModal;
